package devops

import (
	"log"
	"strings"
	"time"

	"away.wei/minidevpos/global"
)

type DevOpsTask struct {
	taskId    int
	projectId int
	deployNum int
}

type DevOpsHub struct {
	DevOpsProjecs    map[int]bool
	DevOpsCancelChan chan int
}

var devopsProjects = make(map[int]bool, 0)

type DevOps struct{}

func (*DevOps) Listener() {
	go func() {
		for {
			<-time.After(time.Second * 3)
			getProjectTask()
		}
	}()
	log.Println("devops task running")
}
func getProjectTask() {
	taskList, _ := projectTaskRep.GetGroupAll()
	for _, v := range taskList {
		_, ok := devopsProjects[v.ProjectId]
		if ok {
			continue
		}

		devopsProjects[v.ProjectId] = true
		go deployer(DevOpsTask{
			taskId:    v.ID,
			projectId: v.ProjectId,
			deployNum: v.Num,
		})
	}
}

func deployer(devopsTask DevOpsTask) {
	defer delete(devopsProjects, devopsTask.projectId)
	updateStatus(devopsTask, status_execing, nil)
	devopsWorkSpace.New(devopsTask)
	status, err := devopsWorkSpace.Build()
	if err != nil {
		updateStatus(devopsTask, status, err)
		return
	}
	status, err = devopsWorkSpace.Deploy()
	updateStatus(devopsTask, status, err)
}

type DevOpsNotify struct {
	Message string `json:"Message"`
	Code    int    `json:"Code"`
}

func updateStatus(devopsTask DevOpsTask, status int, err error) {
	var (
		updateErr = projectTaskRep.UpdateStatus(devopsTask.taskId, status)
		notify    = new(DevOpsNotify)
		msgs      = make([]string, 0)
	)
	notify.Code = status
	if updateErr != nil {
		msgs = append(msgs, updateErr.Error())
	}
	if err != nil {
		msgs = append(msgs, err.Error())
	}

	if len(msgs) == 0 {
		msgs = append(msgs, "完成")
	}
	notify.Message = strings.Join(msgs, "\n")
	global.DevOpsEventAPP.EmitJson("devops_notify", notify)

}
